package tingshu.servlet.album;

import lombok.SneakyThrows;
import tingshu.util.DBUtil;
import tingshu.util.Log;
import tingshu.view_object.UserVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;

@WebServlet("/studio/album/create.do")
public class CreateDoServlet extends HttpServlet {
    @Override
    @SneakyThrows
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        HttpSession session = req.getSession(false);
        UserVO userVO = null;

        if (session != null) {
            userVO = (UserVO) session.getAttribute("currentUser");
        }

        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/plain");
        PrintWriter writer = resp.getWriter();
        if (userVO == null) {
            Log.println("用户未登录");
            writer.println("用户未登录");
            return;
        }

        String title = req.getParameter("title");
        String cover = req.getParameter("cover");

        try (Connection c = DBUtil.connection()) {
            String sql = "insert into albums (uid, title, cover, state) values (?, ?, ?, ?)";
            try (PreparedStatement ps = c.prepareStatement(sql)) {
                ps.setInt(1, userVO.uid);
                ps.setString(2, title);
                ps.setString(3, cover);
                ps.setInt(4, 1);

                Log.println("执行 SQL" + ps);
                ps.executeUpdate();
            }
        }
        writer.println("专辑创建成功");
    }
}
